<?php
/**
 * Created by PhpStorm.
 * User: lg
 * Date: 2018/1/5
 * Time: 10:44
 */

namespace app\bangding\controller;

use EasyWeChat\Foundation\Application;

class Callback extends PublicController
{
    public function login()
    {
        $user = $this->oauth()->user();
        $openid = $user->getId();
        $nickname = $user->getName(); // 对应微信的 nickname
        $img = $user->getAvatar();
        session('wechat.openid', $openid);
        session('wechat.nickname', $nickname);
        session('wechat.head_url', $img);
        $id = session('id');
        $data['openid']=$openid;
        $data['headimg']=$img;
        $data['nickname']=$nickname;
        db('son')->where(['son_id'=>$id])->update($data);
//        $this->redirect(url('bangding/index/haibao'));
        $this->success('绑定成功','bangding/index/haibao');
    }



    //{
//"appid":"wxe5d25f7c7ea9538c",
//"bank_type":"CFT",
//"cash_fee":"1",
//"fee_type":"CNY",
//"is_subscribe":"N",
//"mch_id":"1486343132",
//"nonce_str":"5acdb802a91b3",
//"openid":"oKsHx0AwfE4wa5Pn7zwzPkzR_RM8",
//"out_trade_no":"201804111523461562165",
//"result_code":"SUCCESS",
//"return_code":"SUCCESS",
//"sign":"FD4D4951A139F555E440075B48989730",
//"time_end":"20180411152356",
//"total_fee":"1",
//"trade_type":"JSAPI",
//"transaction_id":"4200000079201804116512370656"}
    //支付回调
    public function notify()
    {
        $payment = $this->paymnet();
        $response = $payment->handleNotify(function ($notify, $successful) {
            trace("支付回调参数：" . json_encode($notify), 'info');
            $order = $notify->out_trade_no;
//            $data['transaction_id']=$notify->transaction_id;
            $data['pay_time']=time();
            $data['status']=1;
            $pay_info = db('order')->where(['order_no' => $order])->find();
            trace("order_info：" . json_encode($pay_info), 'info');
            if (!$pay_info) { // 如果订单不存在
                return 'Order not exist.'; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
            if ($pay_info['status'] == 1||$pay_info['status'] == 2) {
                return true; // 已经支付成功了就不再更新了
            }
            // 用户是否支付成功
            if ($successful) {
                $data['status']=1;
                db('order')->where(['order_id' => $pay_info['order_id']])->update($data);
//                支付成功去发红包
                $hb=$this->sendhb($pay_info);
            } else { // 用户支付失败
                $data['status']=0;
                db('order')->where(['order_id' => $pay_info['order_id']])->update($data);
            }
            return true; // 或者错误消息
        });
        $response->send();
    }

    public function sendhb($order)
    {
        if($order['user_id']==$order['invit_id']){
//            订单购买用户和邀请用户一致不发送红包
            return 0;
        }
        $haibao=db('haibao')->where(['haibao_id'=>$order['haibao_id']])->find();
        if($haibao['hb_one']+$haibao['ff_all']>$haibao['hb_all']){
//            说明剩下的钱不够发了
            return 0;
        }
        $user=db('user')->where(['user_id'=>$order['invit_id']])->find();
        $options = [
            // payment
            'app_id'  => 'wx30e3e6f8a64f58c5',         // AppID
            'payment' => [
                'merchant_id'        => '1486343132',
                'key'                => 'jz2SkjTdMDsmW81p7h5YP6Q8AbzaM9cX',
                'cert_path'          => ROOT_PATH.'/apiclient_cert.pem',
                'key_path'           => ROOT_PATH.'/apiclient_key.pem',
                // ...
            ],
        ];
        $app=new Application($options);

        $luckyMoney = $app->lucky_money;
        $luckyMoneyData = [
            'mch_billno'       => getOrderNo($order['invit_id']),
            'send_name'        => '分享奖励',
            're_openid'        => $user['openid'],
            'total_num'        => 1,  //固定为1，可不传
            'total_amount'     => $haibao['hb_one'],  //单位为分，不小于100
            'scene_id'         =>'PRODUCT_2',
            'wishing'          => '分享奖励',
            'act_name'         => $haibao['name'],
            'remark'           => '邀请越多得越多！'
            // ...
        ];
        $result = $luckyMoney->sendNormal($luckyMoneyData);
        trace($result, 'hongbao');
        $hbfee=$haibao['ff_all']+$haibao['hb_one'];
        db('haibao')->where(['haibao_id'=>$haibao['haibao_id']])->update(['ff_all'=>$hbfee]);
        $hongbao['order_id']=$order['order_id'];
        $hongbao['haibao_id']=$haibao['haibao_id'];
        $hongbao['user_id']=$order['invit_id'];
        $hongbao['fee']=$haibao['hb_one'];
        $hongbao['send_time']=time();
        db('hongbao')->insertGetId($hongbao);
        return true;
    }
}